import json
import re
import execjs
import requests
import time
import redis


def get_ip():
    # 提取代理API接口，获取1个代理IP
    api_url = "https://dps.kdlapi.com/api/getdps/?secret_id=o6ykpp1tqja9zj9g4947&signature=ne52s9ngdvy61nrghkzf7kytjk7c3qgk&num=1&sep=1"
    # 获取API接口返回的代理IP
    proxy_ip = requests.get(api_url).text

    username = "d2769292027"
    password = "8bnrqo2g"
    proxies = {
        "http": "http://%(user)s:%(pwd)s@%(proxy)s/" % {"user": username, "pwd": password, "proxy": proxy_ip},
        "https": "http://%(user)s:%(pwd)s@%(proxy)s/" % {"user": username, "pwd": password, "proxy": proxy_ip}
    }
    return proxies


proxies = get_ip()

# redis_conn = redis.Redis(host='localhost', port=6379, decode_responses=True, db=1)


token = "3490eb6a291aba94cbd569b1fdc6aad5"
appkey = "12574478"
with open("taobao.js", "r", encoding="utf-8") as f:
    js_code = execjs.compile(
        f.read()
    )

headers = {
    "referer": "https://s.taobao.com/search?_input_charset=utf-8&commend=all&ie=utf8&initiative_id=tbindexz_20170306&page=1&preLoadOrigin=https%3A%2F%2Fwww.taobao.com&q=%E9%85%8D%E9%A5%B0&search_type=item&source=suggest&sourceId=tb.index&spm=a21bo.jianhua%2Fa.search_history.d1&ssid=s5-e&suggest_query=&tab=all&wq=",
    "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36"
}
cookies = {
    "wk_cookie2": "191c059fcf51464372fe8b193566868a",
    "wk_unb": "UUpgRKmeg4r6ijoFuA%3D%3D",
    "_m_h5_tk": f"{token}_1752765684468",
    "_m_h5_tk_enc": "6fc5b29f081f74811e70035de75bebd1",
    "sca": "b6ac0e4a",
}
url = "https://h5api.m.taobao.com/h5/mtop.relationrecommend.wirelessrecommend.recommend/2.0/"
count = 0
max_retries = 3  # 最大重试次数

for page in range(1, 101):
    retries = 0
    while retries < max_retries:
        params = {
            "jsv": "2.7.4",
            "appKey": appkey,
            "t": "1752755665353",
            "sign": "e74207430ea7da0878c8facf6ca6c6d1",
            "api": "mtop.relationrecommend.wirelessrecommend.recommend",
            "v": "2.0",
            "timeout": "10000",
            "data": "{\"appId\":\"34385\",\"params\":\"{\\\"device\\\":\\\"HMA-AL00\\\",\\\"isBeta\\\":\\\"false\\\",\\\"grayHair\\\":\\\"false\\\",\\\"from\\\":\\\"nt_history\\\",\\\"brand\\\":\\\"HUAWEI\\\",\\\"info\\\":\\\"wifi\\\",\\\"index\\\":\\\"4\\\",\\\"rainbow\\\":\\\"\\\",\\\"schemaType\\\":\\\"auction\\\",\\\"elderHome\\\":\\\"false\\\",\\\"isEnterSrpSearch\\\":\\\"true\\\",\\\"newSearch\\\":\\\"false\\\",\\\"network\\\":\\\"wifi\\\",\\\"subtype\\\":\\\"\\\",\\\"hasPreposeFilter\\\":\\\"false\\\",\\\"prepositionVersion\\\":\\\"v2\\\",\\\"client_os\\\":\\\"Android\\\",\\\"gpsEnabled\\\":\\\"false\\\",\\\"searchDoorFrom\\\":\\\"srp\\\",\\\"debug_rerankNewOpenCard\\\":\\\"false\\\",\\\"homePageVersion\\\":\\\"v7\\\",\\\"searchElderHomeOpen\\\":\\\"false\\\",\\\"search_action\\\":\\\"initiative\\\",\\\"sugg\\\":\\\"_4_1\\\",\\\"sversion\\\":\\\"13.6\\\",\\\"style\\\":\\\"list\\\",\\\"ttid\\\":\\\"600000@taobao_pc_10.7.0\\\",\\\"needTabs\\\":\\\"true\\\",\\\"areaCode\\\":\\\"CN\\\",\\\"vm\\\":\\\"nw\\\",\\\"countryNum\\\":\\\"156\\\",\\\"m\\\":\\\"pc\\\",\\\"page\\\":"
                    + str(
                page) + ",\\\"n\\\":48,\\\"q\\\":\\\"%E9%85%8D%E9%A5%B0\\\",\\\"qSource\\\":\\\"url\\\",\\\"pageSource\\\":\\\"a21bo.jianhua/a.search_manual.0\\\",\\\"channelSrp\\\":\\\"\\\",\\\"tab\\\":\\\"all\\\",\\\"pageSize\\\":48,\\\"totalPage\\\":100,\\\"totalResults\\\":4800,\\\"sourceS\\\":\\\"0\\\",\\\"sort\\\":\\\"_coefp\\\",\\\"bcoffset\\\":\\\"\\\",\\\"ntoffset\\\":\\\"\\\",\\\"filterTag\\\":\\\"\\\",\\\"service\\\":\\\"\\\",\\\"prop\\\":\\\"\\\",\\\"loc\\\":\\\"\\\",\\\"start_price\\\":null,\\\"end_price\\\":null,\\\"startPrice\\\":null,\\\"endPrice\\\":null,\\\"itemIds\\\":null,\\\"p4pIds\\\":null,\\\"p4pS\\\":null,\\\"categoryp\\\":\\\"\\\",\\\"ha3Kvpairs\\\":null,\\\"myCNA\\\":\\\"TbnrIB71MyICAXug4VWWatqY\\\",\\\"screenResolution\\\":\\\"1920x1080\\\",\\\"userAgent\\\":\\\"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36\\\",\\\"couponUnikey\\\":\\\"\\\",\\\"subTabId\\\":\\\"\\\",\\\"np\\\":\\\"\\\"}\"}",
        }
        t = int(time.time() * 1000)
        params["t"] = t
        sign = js_code.call("get_sign", token, t, appkey, params["data"])
        params["sign"] = sign
        try:
            response = requests.get(url, headers=headers, cookies=cookies, params=params, proxies=proxies)
            print(response.status_code)
            py_obj = response.json()
            # print(py_obj)
            for item in py_obj.get("data").get("itemsArray"):
                count += 1
                title_str = item.get("title")
                if title_str:
                    title = re.sub(r'<[^>]+>', '', title_str)
                    print(page, count, title)
            break
        except Exception as e:
            print(f"错误页{page}, 重试次数{retries}, 错误原因{e}")
            retries += 1
            if retries < max_retries:
                print("获取新代理中....")
                proxies = get_ip()  # 获取新的代理
                time.sleep(2)  # 等待一段时间再重试
            else:
                print(f"重试{retries}次，跳过本页，进入下一页")
